<template>
    <view>
        <view class="u-page">
            <view class="loading-icon" v-if="!formItems">
                <u-loading-icon></u-loading-icon>
            </view>
            
            <view class="top-tip" v-show="tip">{{tip}}</view>
            
            <view class="topper">
                <view class="topperItems" v-for="(item, index) in topperItems" :key="index" :style="item.style" :class="item.clz" v-show="!item.hide">
                    <view class="leftIcon" v-if="item.icon" :style="item.icon.style">
                        <image v-if="item.icon.url" :src="item.icon.url" :style="item.icon.iconStyle" mode="aspectFill"></image>
                    </view>
                    <view class="rightText" v-if="item.text">{{item.text}}</view>
                </view>
            </view>

            <view class="formPage" v-if="formItems && model && !viewMode">
                <!-- :rules="rules" -->
                <u--form labelPosition="left" :model="model" ref="form1" reef="form1">
                    <view v-for="(item, index) in formItems" :key="index" class="fieldItem"
                     :class="{candelete: item.candelete}" v-show="!item.hide">
                        <view class="delete-btn" v-if="item.candelete">
                            <view class="delete-btn"><u-button type="error" size="mini" text="删除" @click="deleteExtField(item)"></u-button> </view>
                        </view>
                        <view v-if="!item.prop" :class="item.clz" :style="item.style">
                            <view class="label" v-if="item.label" @click="handleCoustomFieldClick(item)">{{item.label}}</view>
                            <u-divider :dot="true" v-if="item.clz=='dot'"></u-divider> 
                        </view>
                        <view v-else>
                            <view :class="[item.prop, {address: item.address}]" v-if="item.type == 'text'">
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="item.required" @click="openPicker(item)">
                                    <u--input v-model="model[item.prop]" :placeholder="item.placeholder" border="none" :readonly="item.readonly"
                                    @blur="onItemPutComplete(item)"></u--input>
                                    <view class="getcode" v-if="item.prop == 'dxyzNo'">
                                        <u-button @tap="getCode(item)" type="success" :disabled="validateBtnDisabled" size="small">{{ validateTips }}</u-button>
                                    </view>
                                    <view class="getAddress" v-if="item.address" @click="openChoosemap(item)">
                                        <u-icon name="map-fill" color="#2979ff" size="20"></u-icon>
                                    </view>
									<!-- #ifdef H5 -->
									<view class="getAddress" v-if="item.h5Button" @click="execH5Foo(item)">
									    <u-icon :name="item.h5Button" color="#2979ff" size="20"></u-icon>
									</view>
									<!-- #endif -->
                                </u-form-item>
                            </view>
                            
                            <view :class="item.prop" class="textareaField" v-else-if="item.type == 'textarea'">
                                <u-form-item :prop="item.prop" borderBottom>
                                    <view class="text-area-label">
                                        <text class="require" v-show="item.required">*</text>
                                        <text class="label">{{item.label}}</text>
                                        <text class="subLabel" :style="subLabelStyle">{{item.subLabel}}</text>
                                    </view>
                                    <u--textarea placeholder-class="pcs" v-model="model[item.prop]" :height="item.height || 70" :maxlength="item.maxlength || 140" :placeholder="item.placeholder" :readonly="item.readonly"></u--textarea>
                                </u-form-item>
                            </view>
                        
                            <view v-else-if="item.type == 'date' || item.type == 'time' || item.type == 'carNo' || item.type == 'tree-picker'">
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="item.required" @click="openPicker(item)">
                                    <u--textarea placeholder-class="pcs" v-model="model[item.prop]" :placeholder="item.placeholder" border="none" disabled></u--textarea>
                                    <u-icon slot="right" name="arrow-right"></u-icon>
                                </u-form-item>
                            </view>
                            <view v-else-if="item.type == 'areapicker'">
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="item.required">
                                    <regionPicker :ref="'picker' + item.prop" :multiIndex_="item.provinceCityArea" @selecteRegion_="selecteProvinceCityArea($event, item)" :column_="3"></regionPicker>
                                    <u-icon slot="right" name="arrow-right"></u-icon>
                                </u-form-item>
                            </view>
                            <view v-else-if="item.type == 'checkbox'">
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="item.required">
                                    <view class="options">
                                        <view class="option" v-for="(op, opindex) in item.options" :key="opindex" :class="{ active: op.active }" @click="optionChecked(item, opindex)">
                                            {{ op.name }}
                                        </view>
                                    </view>
                                </u-form-item>
                            </view>
                            <view v-else-if="item.type == 'picker'">
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="item.required" @click="openPicker(item)">
                                    <u--input v-model="model[item.prop]" :placeholder="item.placeholder" border="none" disabled></u--input>
                                    <u-icon slot="right" name="arrow-right"></u-icon>
                                </u-form-item>
                                <my-u-picker immediateChange :show="item.showPicker" keyName="name" :ref="item.prop + 'Picker'" :columns="item.columns" @confirm="openPickerConfirm($event, item)"
                                @cancel="onPickerClose(item)" @close="onPickerClose(item)" closeOnClickOverlay></my-u-picker>
                            </view>
                            <view class="imageUploader" v-else-if="item.type == 'image'">
                                <u-form-item :label="item.label" borderBottom labelWidth="120" :prop="item.prop" :required="item.required">
                                    <view class="placeholder">{{item.placeholder}}</view>
                                    <u-upload :sizeType="['compressed']" :fileList="item.fileList" @afterRead="afterFileRead($event, item)" 
                                    :readonly="item.readonly" :disabled="item.readonly" :deletable="!item.readonly"
                                    @delete="afterFileDelete($event, item)" multiple :maxCount="item.limit"></u-upload>
                                    <!-- multiple :maxCount="10" -->
                                </u-form-item>
                            </view>
                            <view v-else-if="item.type == 'xq-picker'">
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="item.required" @click="openPicker(item)">
                                    <u--input v-model="model[item.prop]" :placeholder="item.placeholder" border="none" disabled></u--input>
                                    <u-icon slot="right" name="arrow-right"></u-icon>
                                </u-form-item>
                            </view>

                            <view :class="item.prop" class="textareaField" v-else-if="item.type == 'huoche'">
                                <u-form-item :prop="item.prop" borderBottom>
                                    <view class="text-area-label">
                                        <text class="require" v-show="item.required">*</text>
                                        <text class="label">{{item.label}}</text>
                                        <text class="subLabel" :style="item.subLabelStyle">{{item.subLabel}}</text>
                                    </view>
                                   <huocheType @confirm="onHuocheTypeConfirm($event, item)" :radio-second="true"></huocheType>
                                </u-form-item>
                            </view>
                        </view>
                    </view>
                </u--form>
                
                <!-- 同行人员 -->
                <view class="txry" v-for="(jtcyItem, jtcyIndex) in jtcyArray" :key="jtcyIndex" v-show="!jtcyItem.deleted">
                    <u-divider text="同行人员" textPosition="left" textColor="#2979ff" lineColor="#2979ff"></u-divider>
                    <u--form labelPosition="left"
                        :model="jtcyItem.model" :ref="'jtcyForm' + jtcyIndex" :reef="'jtcyForm' + jtcyIndex">
                        <view :class="item.prop" v-for="(item, index) in jtcyItem.formItems" :key="index">
                            <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="item.required">
                                <u--input v-model="jtcyItem.model[item.prop]" :placeholder="item.placeholder" border="none" :readonly="item.readonly"></u--input>
                            </u-form-item>
                        </view>
                    </u--form>
                    <view class="delete-btn"><u-button type="error" size="mini" text="删除" @click="deleteJytc(jtcyItem)"></u-button> </view>
                    <!-- <u-divider :dot="true"></u-divider> -->
                </view>
                
                <u-code :seconds="30" ref="uCode" reef="uCode" @change="codeChange" change-text="XS获取" @start="validateBtnDisabled = true" @end="validateBtnDisabled = false"></u-code>
                
                <u-datetime-picker @confirm="datePickerConfirm"	@close="showDatePicker = false"	@cancel="showDatePicker = false" :show="showDatePicker" :value="datePickerModel" mode="date" closeOnClickOverlay></u-datetime-picker>
                <u-datetime-picker @confirm="timePickerConfirm"	@close="showTimePicker = false"	@cancel="showTimePicker = false" :show="showTimePicker" :value="timePickerModel" mode="datetime" closeOnClickOverlay></u-datetime-picker>

                <my-u-picker :show="showXqPicker" keyName="name" ref="xqPicker" reef="xqPicker" :columns="xqColumns" @confirm="onXqConfirm" @change="onXqChange" @cancel="showXqPicker = false" @close="showXqPicker = false" closeOnClickOverlay></my-u-picker>
            
                <TrailerKeyboard 
                    :show.sync="showTrailerKeyboard" :vehicleNo="trailerNo" @confirm="vehicleKeyboardConfirm" vehicleType="car">
                </TrailerKeyboard>
            
            </view>

            <!-- ----------------------------------------------------------------------- -->

            <!-- 浏览的模式 -->
            <view class="formPage" v-if="formItems && viewMode">
                <u--form labelPosition="left" ref="form2">
                    <view v-for="(item, index) in formItems" :key="index" v-show="!item.hide">
                        <view v-if="!item.prop && !item.click" :class="item.clz" :style="item.style">
                            <view class="label" v-if="item.label">{{item.label}}</view>
                            <u-divider :dot="true" v-if="item.clz=='dot'"></u-divider> 
                        </view>
                        <view class="fieldItem" v-else>
                            <view class="edit-btn" v-if="item.editWhenView">
                                <view class="delete-btn"><u-button type="primary" size="mini" text="修改" @click="editSingleField(item)"></u-button> </view>
                            </view>
                            <view class="textareaField" v-if="item.type == 'huoche'">
                                <u-form-item borderBottom>
                                    <view class="text-area-label">
                                        <text class="label">{{item.label}}</text>
                                    </view>
                                   <huocheType mode="read" :init-value="item.value"></huocheType>
                                </u-form-item>
                            </view>

                            <view v-else-if="item.type == 'image'">
                                <u-form-item :label="item.label" borderBottom labelWidth="120">
                                    <u-upload :fileList="item.fileList" readonly disabled :deletable="false"
                                     multiple :maxCount="item.limit"></u-upload>
                                    <!-- multiple :maxCount="10" -->
                                </u-form-item>
                            </view>
                            <view :class="item.prop" v-else>
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120">
                                    <!-- <u--input v-model="item.value" border="none" :readonly="true"></u--input> -->
                                    <view style="text-align:right;width: 100%;">
                                        {{item.value}}
                                    </view>
                                </u-form-item>
                            </view>
                        </view>
                    </view>
                </u--form>
                <view class="viewBottomBtn" v-if="viewBottomBtn" v-show="viewBottomBtn.show" :style="viewBottomBtn.style">
                    <view class="btn" v-for="(btn, btnIndex) in viewBottomBtn.btns" :key="btnIndex" :style="btn.style" v-show="btn.show">
                        <u-button :type="btn.type" :text="btn.text" @click="viewBottomButtonClick(btn)"></u-button>
                    </view>
                </view>
            </view>
            
            <!-- 底部提醒 -->
            <view class="submitTipInfo" v-if="submitTipInfo" v-show="!submitTipInfo.hide">
                <view class="title" v-if="submitTipInfo.label">{{submitTipInfo.label}} <text class="required" v-if="submitTipInfo.required">*</text> </view>
                <view class="text" v-if="submitTipInfo.text">{{submitTipInfo.text}}</view>
                <view class="checkbox">
                    <u-checkbox-group v-model="submitTipInfo.comfirm" placement="column" @change="submitTipCheckboxChanged" >
                        <u-checkbox :customStyle="{marginBottom: '8px'}" shape="circle" :label="submitTipInfo.confirmText" name="submitConfirm" >
                        </u-checkbox>
                    </u-checkbox-group>
                </view>
            </view>
            
            <!-- 通用弹出层 -->
            <view class="commonpopup" v-if="commonPopupInfo">
                <u-popup :show="commonPopupInfo.show" mode="center"
                        @close="closeCommonPopup()" @open="openCommonPopup()"  :closeOnClickOverlay="false">
                    <view v-if="commonPopupInfo.popupInfo" class="commonPopInfo">
                            <view class="label" :style="commonPopupInfo.popupInfo.labelStyle">{{commonPopupInfo.popupInfo.label}}</view>
                            <view class="body">
                                <text class="textarea" space="emsp">{{commonPopupInfo.popupInfo.text}} </text>
                                <view class="checkbox" v-if="commonPopupInfo.popupInfo.wait">
                                    请先仔细阅读上文，还剩{{commonPopupInfo.popupInfo.wait}}秒
                                </view>
                                <view class="checkbox" v-if="!commonPopupInfo.popupInfo.wait && commonPopupInfo.popupInfo.showConfirm">
                                    <u-checkbox-group v-model="commonPopupInfo.popupInfo.comfirm" placement="column" @change="commonPopupCheckboxChanged" >
                                        <u-checkbox :customStyle="{marginBottom: '8px'}" shape="circle" name="readbeforeConfirm" :label="commonPopupInfo.popupInfo.confirmText">
                                        </u-checkbox>
                                    </u-checkbox-group>
                                </view>
                                <view class="confirmBtn">
                                    <template v-if="commonPopupInfo.popupInfo.extButton">
                                         <u-button :type="b.type || 'primary'" v-for="(b, bi) in commonPopupInfo.popupInfo.extButton" :key="bi"
                                            @click="viewBottomButtonClick(b)"
                                            :disabled="commonPopupInfo.popupInfo.wait!=0 || b.needCheck && commonPopupInfo.popupInfo.showConfirm && !commonPopupInfo.popupInfo.confirm"
                                            >{{b.label}}</u-button>
                                    </template>
                                    <u-button type="primary"
                                    @click="closeCommonPopup()"
                                    :disabled="commonPopupInfo.popupInfo.wait!=0 || commonPopupInfo.popupInfo.showConfirm && !commonPopupInfo.popupInfo.confirm"
                                    >{{commonPopupInfo.popupInfo.confirmBtnText || '确定'}}</u-button>
                                </view>
                            </view>
                    </view>
                </u-popup>
            </view>

            <view class="bottom-area" v-if="formItems && openId && !viewMode">
                <u-button text="添加同行人员" @click="addJtcy()" v-if="showTxry"></u-button>
                <u-button text="返回首页" @click="back()" v-if="!showTxry && showBack"></u-button>
                <u-button type="primary" text="提交" @click="submit()" :disabled="submitTipInfo && (!submitTipInfo.hide && !submitTipInfo.confirm)"></u-button>
            </view>
        </view>
    </view>
</template>

<script>
import getLocation from '@/utils/getLocation.js'
import regionPicker from '@/components/region-picker/region-picker.vue';
import TrailerKeyboard from '@/components/TrailerKeyboard/index.vue';
import huocheType from '@/components/huocheType/index.vue';
import formUtils from '@/utils/formUtils.js';
import sceneMixins from '@/utils/sceneMixins';
import { mapState, mapMutations } from 'vuex';
export default {
    components: {
        regionPicker, TrailerKeyboard, huocheType
    },
    mixins: [sceneMixins, getLocation],
    options: { styleIsolation: 'shared' },
    data() {
        return {
            // 只读模式
            viewMode: false,

            formItems: '',
            model: '',
            // rules: '',
            // 日期工具
            showDatePicker: false,
            datePickerModel: '',
            showTimePicker: false,
            timePickerModel: '',
            // provinceCityArea: ['11', '11007', '11007008'],
            // 获取验证码
            validateBtnDisabled: false,
            validateTips: '',
            // 村社区选择
            showXqPicker: false,
            xqColumns: [],
            // 车牌选择
            showTrailerKeyboard: false,
            trailerNo: '',

            openId: '',
            
            jtcyArray: [],
            jtcyModel: {},

            showTxry: false,
            tip: '',
            submitTipInfo: '',
            viewBottomBtn: '',
            // 通用弹出层
            commonPopupInfo: '',
            showBack: false,
            
            topperItems: []
        };
    },
    computed: {
        ...mapState(['hasLogin', 'globalConfig'])
    },
    onShow(e) {
        let pages = getCurrentPages();
        let currPage = pages[ pages.length - 1];
        // #ifdef MP-WEIXIN
        if(currPage.data.callBackData){
            this.treePickerConfirm(currPage.data.callBackData);
        }
        currPage.data.callBackData = undefined;
        // #endif

        var vm = this;
        
        if (vm.commonPopupInfo && vm.commonPopupInfo.popupInfo) {
            if (vm.commonPopupInfo.popupInfo.wait) {
                global.beforeWaitTo = setInterval(() => {
                    if (vm.commonPopupInfo.popupInfo.wait) {
                        vm.commonPopupInfo.popupInfo.wait--
                    } else {
                        clearInterval(global.beforeWaitTo);
                    }
                }, 1000);
            }
        }
    },
    destroyed() {
        clearInterval(global.beforeWaitTo);
    },
    onLoad(options) {
        var vm = this;
        vm.syCity = options.syCity;

        if (options.query) {
            var queryObj = JSON.parse(decodeURIComponent(options.query));
            vm.queryObj = queryObj; 
            Object.assign(options, queryObj);
        }
        
        if (options.title) {
            uni.setNavigationBarTitle({
                title: options.title
            });
        }
        vm.doWxLogin().then(res => {
            vm.openId = res.openId;
        });
        // debugger
        if (options.id && options.viewMode != 'edit') {
            vm.viewMode = true;
            vm.loadDetail(options.id);
            return;
        }

        vm.getXqColumns();

        if (options.loadJSON) {
            vm.getAndLoad('申报的配置json', options.loadJSON, function (res) {
                var formItems = res.formItems;
                vm.showTxry = res.txry;
                // debugger
                vm.showBack = res.showBack;
                vm.txryFormItems = res.txryFormItems;
                vm.tip = res.tip || '';
                vm.submitTipInfo = res.submitTipInfo;
                vm.pageJSON = res;
                
                formItems.forEach(n => {
                    if (!n.prop) {
                        return;
                    }
                    if (n.optionApi && !n.lazySearch) {
                        n.optionApi = n.optionApi.replace('【openId】', vm.openId);
                        vm.getAndLoad('读取option列表', n.optionApi, function (res) {
                            n.options = res.data;
                            if (n.type == 'picker') {
                                n.columns = [n.options];
                            }
                        });
                    } else if (n.type == 'picker' && n.options) {
                        n.columns = [n.options];
                    }
                    // 设置一些初始值
                    if (n.type == 'checkbox') {
                        if (!n.options.map) {
                            n.options = n.options.split('$').map((m, i) => {
                                return {
                                    name: m.split(':')[1],
                                    active: !i,
                                    value: m.split(':')[0],
                                };
                            })
                        } else {
                            n.options = n.options.map((o, i) => {
                                return { name: o, active: !i };
                            });
                        }
                    }
                    if (n.type == 'picker') {
                        n.showPicker = false;
                    }
                    if (n.type == 'areapicker') {
                        n.provinceCityArea = [];
                    }
                    if (n.type == 'image') {
                        !n.limit && (n.limit = 1);
                        n.fileList = [];
                    }
                });
                vm.formItems = formItems;
                vm.generateModelAndRules();
                // debugger
                if (res.initInfoApi) {
                    vm.initFormInfo(res.initInfoApi);
                }
                if (res.gaozhiBefore) {
                    vm.initCommonPopup(res.gaozhiBefore, true);
                }
            });
        }
    },
    methods: {
        onItemPutComplete: function (item) {
            var vm = this;
            if (item.loadInfoApi) {
                vm.form1.validateField(item.prop, (res) => {
                    if (!res.length) {
                        function getReplaceUrl (url) {
                            url = url.replace('【openId】', vm.openId);
                            return url.replace(/【([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*】/g, function (d) {
                                var prop = d.slice(1, -1);
                                var value = vm.model[prop];
                                return value || '';
                            });
                        }
                        
                        var api = getReplaceUrl(item.loadInfoApi);
                        vm.getAndLoad('加载信息', api + vm.model[item.prop], function (res) {
                            if (res.data) {
                                vm.setBindValues(res.data, item);
                            }
                        })
                    }
                })
            }
            if (item.onChange) {
                this.handleItemOnChange(item);
            }

        },
        initFormInfo: function (apiUrl) {
            var vm = this;
            apiUrl = apiUrl.replace('【openId】', vm.openId);
            
            let routes = getCurrentPages();
            let curParam = routes[routes.length - 1].options;
            
            apiUrl = apiUrl.replace(/\{([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*\}/g, function (d) {
                var prop = d.slice(1, -1);
                if (prop == 'openId') {
                    return vm.openId;
                }
                return curParam[prop];
            });
            if (apiUrl.includes('undefined')) {
                return;
            }
            uni.showLoading({title: '正在加载表单'});
            vm.getAndLoad('获取列表', apiUrl, function (res) {
                uni.hideLoading();
                if (res.code == 0) {
                    if (res.successTip) {
                        uni.$u.toast(res.successTip);
                    }
                    var keys = Object.keys(res.data);
                    // debugger
                    keys.forEach(n => {
                        // vm.model[n] = res.data[n];
                        vm.setModelValue(n, res.data[n]);
                    });
                    
                } else {
                    uni.showModal({
                        title: '提示',
                        content: res.msg || '表单加载失败',
                        showCancel: false,
                        success: function(res2) {
                            uni.navigateBack();
                        }
                    });
                }
            });
        },
        deleteJytc (item) {
            item.deleted = true;
        },
        initCommonPopup: function (popupInfo, open) {
            var vm = this;
            vm.commonPopupInfo = {
                show: false,
                popupInfo
            };
            if (open) {
                vm.$nextTick(function(){
                    vm.openCommonPopup();
                })
            }
            
        },
        openCommonPopup: function () {
            var vm = this;
            vm.commonPopupInfo.show = true;
            if (vm.commonPopupInfo.popupInfo.wait) {
                if (process.env.NODE_ENV == 'development') {
                    vm.commonPopupInfo.popupInfo.wait = 3;
                }
                clearInterval(global.beforeWaitTo);
                global.beforeWaitTo = setInterval(() => {
                    if (vm.commonPopupInfo.popupInfo.wait) {
                        vm.commonPopupInfo.popupInfo.wait--
                    } else {
                        clearInterval(global.beforeWaitTo);
                    }
                }, 1000);
            }
            
        },
        closeCommonPopup: function () {
            this.commonPopupInfo.show = false;
        },
        commonPopupCheckboxChanged: function (data) {
            this.commonPopupInfo.popupInfo.confirm = data.length;
        },
        
        vehicleKeyboardConfirm: function (value) {
            this.model[this.currentProp] = value;
            this.showTrailerKeyboard = false;
        },
        
        handleCoustomFieldClick: function (item) {
            var vm = this;
            if (item.click) {
                var fooArr = item.click.split('_');
                var fooName = fooArr[0];
                if (fooName == 'addFields') { // 增加字段
                    vm.addFields(item)
                } else {
                    var fooArgs = fooArr.slice(1);
                    vm[item.click](...fooArgs);
                }
            }
        },
        renameFileds(items) {
            var vm = this;
            var mapSet = {};
            items.forEach(n => {
                if (n.propId) {
                    if (!mapSet[n.propId]) {
                        mapSet[n.propId] = new Set();
                    }
                    mapSet[n.propId].add(n.groupId);
                    
                    var orginItem = vm.formItems.find(m => m.uuid == n.propId); // 找到添加他的按钮					
                    // debugger
                    var num = mapSet[n.propId].size + (orginItem.startFrom == 1 ? 0 : 1);
                    
                    n.copyIndex = num;
                    if (n.groupLabel) {
                        if (!n.orignLabel) { n.orignLabel = n.label};
                        n.label = n.orignLabel + num;
                    }
                }
            });
        },
        deleteExtField: function (item) {
            var vm = this;
            uni.showLoading({ title: '请等待' });
            // 1.把同组的字段删掉
            var props = [];
            vm.formItems = vm.formItems.filter(n => {
                if (n.groupId != item.groupId) {
                    return true;
                } else {
                    props.push(n.prop);
                    if (n.bindId) {
                        var groupId = item.groupId;
                        var suffixItem = vm.formItems.find(n => n.groupId == groupId && n.propEndFix);
                        var suffix = (suffixItem && suffixItem.propEndFix) || '';
                        props = props.concat([].concat(n.bindId).map(m => {
                            return m + suffix;
                        }));
                    }
                    return false;
                }
            });
            vm.renameFileds(vm.formItems);
            // 2. 清空model里面的无效字段
            props.forEach(key => {
                delete vm.model[key];
                delete vm.rules[key];
                vm.$nextTick(function(){
                    vm.getRefCmp('form1').setRules(vm.rules);
                    uni.hideLoading();
                })
            });
        },
        submitTipCheckboxChanged: function (data) {
            this.submitTipInfo.confirm = (data.length != 0);
        },
        addJtcy () {
            
            var vm = this;
            var jtcyItem = {
                deleted: false,
                formItems: JSON.parse(JSON.stringify(vm.txryFormItems))
            };
            var currentIndex = vm.jtcyArray.length;
            var {rules, model} = formUtils.generateModelAndRules(jtcyItem.formItems);
            jtcyItem.formName = 'jtcyForm' + currentIndex;
            jtcyItem.model = model;
            vm.jtcyArray.push(jtcyItem);

            vm.$nextTick(function(){
				setTimeout(() => {
					vm.getRefCmp(jtcyItem.formName).setRules(rules);
				}, 1000);
            });
        },
        codeChange(text) {
            this.validateTips = text;
        },
        getXqColumns() {
            var vm = this;
            vm.getAndLoad('获取小区', '/mobile/h5/covid19/apiZzsb/getXqAddr.jsp?type=szqs', function(res) {
                vm.xqColumns = [res.data, res.data[0].child];
            });
        },
        onXqConfirm(e) {
            var item = this.formItems.find(n => (n.prop == this.currentProp));
            this.model[item.prop] = e.value[1].name;
            var propsuffix = item.propEndFix || '';
            if (item.bindId) {
                if (item.bindId[0] + propsuffix) {
                    this.model[item.bindId[0] + propsuffix] = e.value[1].id;
                }
                if (item.bindId[1] + propsuffix) {
                    this.model[item.bindId[1] + propsuffix] = e.value[1].gridId;
                }
            } else {
                this.model['hourseId' + propsuffix] = e.value[1].id;
                this.model['gridId' + propsuffix] = e.value[1].gridId;
            }
            

            this.showXqPicker = false;
        },
        onXqChange(e) {
            const {
                columnIndex,
                index,
                // 微信小程序无法将picker实例传出来，只能通过ref操作
                picker = this.getRefCmp('xqPicker')
            } = e;
            // debugger
            if (columnIndex === 0) {
                picker.setColumnValues(1, this.xqColumns[0][index].child);
            }
        },
        onHuocheTypeConfirm: function (data, item) {
            this.model[item.prop] = data;
        },
        getCode(item) {
            var vm = this;
			var uCode = vm.getRefCmp('uCode');
            if (uCode.canGetCode) {
                // 模拟向后端请求验证码
                var phoneFieldProp = item.phoneProp || 'phone';
                vm.getRefCmp('form1').validateField(phoneFieldProp, function(res) {
                    // debugger
                    if (!res.length) {
                        uni.showLoading({
                            title: '正在获取验证码'
                        });

                        vm.getAndLoad('获取验证码', `/mobile/h5/covid19/apiZzsb/sendMsg.jsp?openId=${vm.openId}&phone=` + vm.model[phoneFieldProp], function(res) {
                            uni.hideLoading();
                            if (res.success) {
                                uCode.start();
                                uni.$u.toast('验证码已发送');
                            } else {
                                uni.$u.toast(res.msg || '验证码发送失败');
                            }
                        });
                    }
                });
            }
        },
        afterFileRead: function(data, item) {
            var vm = this;
            data.file.forEach(file => {
                vm.uploadFile(file.url, res => {
                    if (!res.error) {
                        item.fileList.push({
                            path: res.path,
                            url: vm.API_PREFIX + res.path
                        });
                        vm.model[item.prop] = item.fileList.map(n => n.path).join(',');
                    } else {
                        uni.$u.toast('上传失败');
                    }
                });
            });
            
            // item.fileList = [];
            
            // item.fileList = [...data.file];
        },
        afterFileDelete: function(data, item) {
            item.fileList.splice(data.index, 1);
            this.model[item.prop] = item.fileList.map(n => n.path).join(',');
        },
        selecteProvinceCityArea(data, item) {
            item.provinceCityArea = data.code;
            var areaCode = data.code.length ? data.code.slice(-1)[0] : '';
            this.model[item.prop] = data.name.join('-');
            if (item.bindId) {
                var propsuffix = item.propEndFix || '';
                this.model[item.bindId + propsuffix] = areaCode;
            }
            var vm = this;
            if (item.onConfirmApi) {
                vm.getAndLoad('触发api', item.onConfirmApi + areaCode, function (res) {
                    if (item.handleOnConfirm) {
                        item.handleOnConfirm.onChange && vm.handleItemOnChange(item.handleOnConfirm, res.data);
                    }
                });
            }
        },
        optionChecked: function(item, opindex) {
            item.options.forEach((n, i) => {
                n.active = i == opindex;
            });
            var checkItem = item.options[opindex];
            this.model[item.prop] = checkItem.value || checkItem.name;
            if (item.onChange) {
                this.handleItemOnChange(item);
            }
        },
        handleItemOnChange: function (field, judgeResult) {
            var vm = this;
            field.onChange.forEach((item => {
                var judgeValue = judgeResult != undefined ? judgeResult : vm.model[field.prop];
                var judgeWhen = item.when ? item.when.includes(judgeValue) : judgeValue != field.originValue;;
                // debugger
                if (item.type == 'changeRequired') {
                    var targetField = vm.formItems.find(n => n.prop == item.field);
                    if (targetField) {
                        vm.$set(targetField, 'required', judgeWhen);
                    }
                }
                else if (item.type == 'changeHide') {
                    var targetField = vm.formItems.find(n => n.prop == item.field);
                    if (targetField) {
                         vm.$set(targetField, 'hide', judgeWhen);
                    }
                }
                else if (item.type == 'changeShow') {
                    var targetField = vm.formItems.find(n => n.prop == item.field);
                    if (targetField) {
                        vm.$set(targetField, 'hide', !judgeWhen);
                    }
                }
                else if (item.type == 'changeLabel') {
                    var targetField = vm.formItems.find(n => n.prop == item.field);
                    if (targetField) {
                        targetField.label = judgeWhen ? item.value : item.valueElse
                    }
                } else if (item.type == 'changeSubmitTipInfo') {
                    var value = judgeWhen ? item.value : (item.valueElse || '');
                    if (item.type2 == 'show') {
                      vm.submitTipInfo.hide = !value;
                    }
                } else if (item.type == 'changeFieldAttr') {
                    var targetField = vm.formItems.find(n => n.prop == item.field);
                    if (targetField) {
                        targetField[item.fieldAttr] = judgeWhen ? item.fieldValue : (item.elseValue || '');
                    }
                }
            }));
        },
        openPicker: function(item) {
            if (item.readonly) {return;}
            this.currentProp = item.prop;
            var currentVal = this.model[item.prop];
            var hideKeyBorad = true;
            if (item.type == 'date') {
                if (currentVal) {
                    this.datePickerModel = new Number(new Date(currentVal));
                } else {
                    this.datePickerModel = new Number(new Date());
                }
 
                this.$nextTick(function() {
                    this.showDatePicker = true;
                });
            } if (item.type == 'time') {
                if (currentVal) {
                    this.timePickerModel = new Number(new Date(currentVal));
                } else {
                    this.timePickerModel = new Number(new Date());
                }
                this.$nextTick(function() {
                    this.showTimePicker = true;
                });
            } else if (item.type == 'areapicker') {
                this.showAreaPicker = true;
            } else if (item.type == 'xq-picker') {
                this.showXqPicker = true;
            } else if (item.type == 'picker') {
                item.showPicker = true;
            } else if (item.type == 'carNo') {
                this.trailerNo = this.model[this.currentProp];
                this.$nextTick(function() {
                    this.showTrailerKeyboard = true;
                });
            } else if (item.type == 'tree-picker') {
                if (!item.options && !item.lazySearch) {
                    uni.$u.toast(item.nullPlaceholder || '无可供选项，请稍后或联系管理员');
                } else {
                    if (item.lazySearch) {
                        uni.setStorageSync('pickerOptions', item.options);
                        uni.setStorageSync('currentPicked', item.value || []);
                        if (item.pickerPage) {
                            uni.navigateTo({ url: item.pickerPage });
                        } else {
                            uni.navigateTo({ url: '/pages/tree/index?' + item.treePickerQueryString +
                            '&autoSearch=' + item.autoSearch + '&title=' + item.placeholder + 
                            '&loadApi=' + encodeURIComponent(this.__getReplaceUrl(item.optionApi)) });
                        }
                    } else {
                        uni.setStorageSync('pickerOptions', item.options);
                        uni.setStorageSync('currentPicked', item.value || []);
                        uni.navigateTo({ url: '/pages/tree/index?title=' + item.placeholder });
                    }
                }
            } else if (item.address) {
                var propsuffix = item.propEndFix || '';
                if (!this.model[item.prop] || (item.bindId && !this.model[item.bindId[0] + propsuffix])) {
                    this.openChoosemap(item);
                } else {
                    hideKeyBorad = false; // 用户继续填写
                }
            } else {
                hideKeyBorad = false;
            }
            hideKeyBorad && this.hideKeyboard();
        },
        openChoosemap: function (item) {
            var vm = this;
            uni.chooseLocation({
                success: res => {
                    vm.model[item.prop] = res.address;
                    if (item.bindId) {
                        var propsuffix = item.propEndFix || '';	
                        vm.model[item.bindId[0] + propsuffix] = res.longitude;
                        vm.model[item.bindId[1] + propsuffix] = res.latitude;
                    }
                 }
            });
        },
        openPickerConfirm: function (e, item) {
            var selectValue = e.value[0];
            if (typeof selectValue == 'string') {
                this.model[item.prop] = selectValue;
            } else {
                this.model[item.prop] = selectValue.name;
            }
            var propsuffix = item.propEndFix || '';
            if (item.bindId) {
                this.model[item.bindId + propsuffix] = selectValue.id;
            }
            item.showPicker = false;
            if (item.onChange) {
                this.handleItemOnChange(item);
            }
        },
        datePickerConfirm: function(value) {
            var item = this.formItems.find(n => (n.prop == this.currentProp));
            this.model[item.prop] = this.$Util.getFmtDate(new Date(value.value));
            this.showDatePicker = false;
            this.form1.validateField(item.prop);
            this.onItemPutComplete(item);
        },
        timePickerConfirm: function(value) {
            var item = this.formItems.find(n => (n.prop == this.currentProp));
            this.model[item.prop] = this.$Util.getFmtDate(new Date(value.value), 'yyyy-MM-dd hh:mm');
            this.showTimePicker = false;
            this.form1.validateField(item.prop);
            this.onItemPutComplete(item);
        },
        treePickerConfirm: function (data) {
            var item = this.formItems.find(n => (n.prop == this.currentProp));
            this.model[item.prop] = data.map(n => n.name).join(',');
            item.value = data[0];
            // debugger
            if (item.bindId) {
                var propsuffix = item.propEndFix || '';
                this.model[item.bindId + propsuffix] = data[0].id;
            } else {
                this.setBindValues(data[0], item);
            }
        },
        
        setBindValues: function (sourceData, item, suffix) {
            var vm = this;
            var bindIdMap = item.bindIdMap;
            if (!bindIdMap && item.addFields) {
                bindIdMap = {};
                item.addFields.forEach(n => {
                   if (n.prop) {
                       bindIdMap[n.prop] = n.prop;
                   }
                   if (n.bindIdMap) {
                       bindIdMap = Object.assign(bindIdMap, n.bindIdMap)
                   }
                   if (n.bindId) {
                       [].concat(n.bindId).forEach(key => {
                            bindIdMap[key] = key;
                       });
                   }
                });
            }
            if (bindIdMap) {
                var keys = Object.keys(bindIdMap);
                var propsuffix = suffix || (item.propEndFix || '');
                keys.forEach((key) => {
                    var targetProp = bindIdMap[key] + propsuffix;
                    vm.setModelValue(targetProp, sourceData[key]);
                });
            }
        },
        setModelValue: function (prop, value) {
            var vm = this;
            if (uni.$u.test.array(value)) {
                vm.setArrayModelValue(prop, value);
                return;
            }
            vm.model[prop] = value;
            var item = this.formItems.find(n => n.prop == prop);
            item && (item.originValue = value);
            if (item && item.type == 'image') {
                item.fileList = value.split(',').map(n => {
                    return {url: vm.API_PREFIX + n, path: n}
                })
            }
            if (item && item.type == 'areapicker') {
                vm.waitVariable('form1').then(() => {
                    setTimeout(() => {
                        vm.model[prop] && vm.$refs['picker' + item.prop][0].setWord(value);
                    }, 1000)
                });
            }
            if (item && item.type == 'image') {
                item.fileList = value ? value.split(',').map(n => {
                    return {url: vm.API_PREFIX + n, path: n}
                }) : []
            }
            if (item && (item.type == 'checkbox')) {
				if (item.options) {
					item.options.forEach(n => {
					   n.active = ((value == n.value) || (value == n.name)); 
					});
					
					var activeItem = item.options.find(n => n.active);
					activeItem && (vm.model[prop] = activeItem.value || activeItem.name);	
				}
            }
            if (item && item.onChange) {
                this.waitVariable('form1').then(() => {
                    this.handleItemOnChange(item);
                })  
            }
        },
        addFields(item) {
            var vm = this;
            if (!item) return;
            uni.showLoading({ title: '请等待' });
            var addFormItems = JSON.parse(JSON.stringify(item.addFields));
            if (!item.extNum) {
                item.extNum = item.startFrom ? (item.startFrom - 1) : 1;
                item.uuid = vm.$Util.uuid(); // 起一个标识 删掉的时候要用
            }
            item.extNum ++; // 计一个编号
            var propEndFix = '_' + item.extNum; // 下标
            var groupUuid = vm.$Util.uuid();
            addFormItems.forEach(n => {
                n.propId = item.uuid; // 所有此类型的uuid
                n.groupId = groupUuid; // 一组的id，以便按钮删除一组
            });
            var {rules, model} = formUtils.generateModelAndRules(addFormItems, '' , propEndFix);
            var insertIndex = vm.formItems.findIndex(n => n == item);
            
            var groupItem = addFormItems.find(n => n.deleteSlot);
            if (groupItem) {
                groupItem.candelete = true;
            } else {
                addFormItems[0].candelete = true;
            }
            
            vm.formItems.splice(insertIndex, 0, ...addFormItems);
            vm.renameFileds(vm.formItems, item.uuid);
            
            var keys = Object.keys(model);
            keys.forEach((key) => {
                vm.$set(vm.model, key, model[key])
            });
            
            var rules2 = Object.assign(vm.rules, rules);
            vm.rules2 = rules2;
            // vm.$refs.form1.setRules(rules2);
            vm.$nextTick(function(){
                uni.hideLoading();
                vm.waitVariable('form1').then(() => {
                    vm.form1.setRules(rules2);
                })
            })
            return groupUuid;
        },
        setArrayModelValue: function (prop, arrayValue) {
            var vm = this;
            var targetItem = vm.formItems.find(n => n.groupProp == prop);
            if (targetItem.autoOpen && !arrayValue.length) {
                vm.addFields(targetItem);
                return;
            }
            arrayValue.forEach(value => {
               var groupId = vm.addFields(targetItem);
               var item = vm.formItems.find(n => n.groupId == groupId && n.propEndFix);
               var suffix = (item && item.propEndFix) || ''
               vm.setBindValues(value, targetItem, suffix);
            });
        },
        onPickerClose: function (item) {
            item.showPicker = false;
        },

        hideKeyboard: function() {
            uni.hideKeyboard();
        },
        generateModelAndRules: function() {
            var vm = this;
            var model = {};
            // 设置model
            this.formItems.forEach(item => {
                // item.key = vm.$Util.uuid();
                if (!item.prop) {
                    return;
                }
                model[item.prop] = item.value || '';
                if (item.type == 'checkbox') {
                    model[item.prop] = item.options[0].value || item.options[0].name;
                }
            });
            this.model = model;

            // 设置rule
            var rules = {};
            this.formItems.forEach(item => {
                if (!item.prop) {return;}
                rules[item.prop] = [];
                if (item.required || item.validatorWhen) {
                    if (!item.validatorWhen) {
                        rules[item.prop].push({ type: 'string', required: true, message: '此项为必填', trigger: ['blur', 'change'] });
                    } else {
                        rules[item.prop].push({
                            type: 'string', 
                            validator: (rule, value, callback) => {
                                if (item.hide) {
                                    return true;
                                }
                                if (item.required && !item.hide) {
                                    return !!value.trim();
                                } else {
                                    return true;
                                } 
                            },
                            message: '此项为必填', 
                            trigger: ['blur', 'change'] 
                        })
                    }
                }
                if (item.validator) {
                    item.validator.forEach(n => {
                        if (n == 'phone') {
                            rules[item.prop].push({
                                type: 'string',
                                validator: (rule, value, callback) => {
                                    // debugger
                                    return (!item.required && !value) || uni.$u.test.mobile(value);
                                },
                                message: '手机号码不正确',
                                trigger: ['change', 'blur']
                            });
                        } else if (n == 'idcard') {
                            rules[item.prop].push({
                                type: 'string',
                                validator: (rule, value, callback) => {
                                    if (item.idcardValidatorWhen) {
                                        var isWhen = !item.idcardValidatorWhen || (vm.model[item.idcardValidatorWhen[0]] == item.idcardValidatorWhen[1]);
                                        if (isWhen) {
                                            return !vm.$Util.idCardValidator(value);
                                        } else {
                                            return true;
                                        }
                                    } else {
										return !vm.$Util.idCardValidator(value);
									}
                                },
                                message: '身份证号码不正确',
                                trigger: ['change', 'blur']
                            });
                        } else if (n == 'section' && item.validatorSetion) {
                            rules[item.prop].push({
                                type: 'string',
                                validator: (rule, value, callback) => {
                                    var currentDate = new Date(value.replace(/-/g, '/')).getTime();
                                    return formUtils.isDateInSection(currentDate, item.validatorSetion);
                                },
                                message: item.validatorSetion[2] || '选择的日期不符合要求',
                                trigger: ['change', 'blur']
                            });
                        }
                    });
                }
            });
            this.rules = rules;
            
            setTimeout(() => {
                vm.getRefCmp('form1').setRules(rules);
				vm.form1 = vm.getRefCmp('form1');
            }, 2000);
        },
        back: function() {
			// #ifdef H5
			history.go(-1);
			// #endif
			// #ifdef MP
			   uni.navigateBack();
			// #endif
        },
        submit: function() {
            var vm = this;
            console.log(this.model);
            vm.throttle();
            var userPosition = vm.$store.state.lnglat;

            // return;
            // 同行人员
            var txryValidatePromise = vm.jtcyArray.map(n => {
                if (!n.deleted) {
                    return vm.getRefCmp(n.formName).validate();
                }
            });
            
            Promise.all([vm.form1.validate(), ...txryValidatePromise]).then(() => {
                var model = JSON.parse(JSON.stringify(this.model));
                delete model.xx;
                model.syCity = vm.syCity;
                model.openId = vm.openId;
                
                vm.jtcyArray.filter(n => !n.deleted).forEach((n, i) => {
                    if (!n.deleted) {
                        var xb = i + 1;
                        model['jtcyName_' + xb] = n.model.jtcyName;
                        model['jtcyIdCard_' + xb] = n.model.jtcyIdCard;
                        model['jtcyPhone_' + xb] = n.model.jtcyPhone;
                    }
                })
                
                if (userPosition) {
                    model.lng = userPosition[0];
                    model.lat = userPosition[1];
                }
                uni.showLoading({
                    title: '正在提交'
                });
                
                var postUrl = '';
                if (vm.pageJSON.submitApi) {
                    postUrl = vm.pageJSON.submitApi;
                } else {
                    postUrl = '/mobile/h5/covid19/apiZzsb/saveSq2.jsp?';
                }

				if (vm.editType == 'edit') {
					model[vm.entityId || 'id'] = vm.id;
                    if (vm.pageJSON.editConfig.editApi) {
                        postUrl = vm.pageJSON.editConfig.editApi;
                    }
				}
                
                let routes = getCurrentPages();
                let curParam = routes[routes.length - 1].options;
                
                postUrl = postUrl.replace(/\{([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*\}/g, function (d) {
                    var prop = d.slice(1, -1);
                    return curParam[prop];
                });

				console.log('save', model);
                
                vm.getAndLoad('保存', postUrl + vm.$Util.stringify(model), function(res) {
                    uni.hideLoading();
                    global.listPageNeedReload = true;
                    if (res.code == 0) {
                        uni.showModal({
                            title: '提示',
                            content: res.msg || '提交成功',
                            showCancel: false,
                            success: function(res2) {
                                // #ifdef H5
                                vm.back();
                                // #endif
                                // #ifdef MP
                                uni.requestSubscribeMessage({
                                    tmplIds: vm.globalConfig.messageTepls,
                                    fail: function (failRes) {
                                        uni.showModal({
                                            title: '提示',
                                            content: '您可以打开消息提醒, 以获取进展提醒',
                                            success: function (res3) {
                                                if (res3.confirm) {
                                                    uni.openSetting({
                                                        withSubscriptions: true
                                                    });
                                                }
                                            }
                                        });
                                    },
                                    complete: function () {
                                        vm.back();
                                    }
                                });
                                // #endif                                
                            }
                        });
                    } else {
                        uni.$u.toast(res.msg);
                    }
                });
            }).catch(e => {
				if (e[0].field) {
					var field = vm.formItems.find(n => n.prop == e[0].field);
					var fieldName = field ? `[${field.label}]：` : '';
					
				}
				uni.$u.toast(fieldName + '有必填项没有填写或填写内容不正确，请先完善。');
			});
        },
        loadDetail: function(id) {
            var vm = this;
            vm.id = id;
            var detailApi = '/mobile/h5/covid19/apiZzsb/getView2.jsp?id=【id】';
            if (vm.queryObj && vm.queryObj.detailApi) {
                detailApi = vm.queryObj.detailApi;
            }
            detailApi = detailApi.replace('【id】',id);

            vm.getAndLoad('详情', detailApi, async function(res) {
                vm.showResponseStr = JSON.stringify(res);
                // 简单的展示
                var formItems = ''
                if (uni.$u.test.array(res.data)) {
                    formItems = res.data;
                } else {
                    if (!res.data.formItems) {
                        // 接口知识简单的给了key - value
                        var result = await new Promise((resolve) => {
                            var loadJSONAPI = vm.queryObj.loadJSON;
                            vm.getAndLoad('loadJSON', loadJSONAPI, (res) => {
                                resolve(res);
                            });
                        });
                        result.formItems.forEach(n => {
                            if (n.prop && res.data[n.prop]) {
                                n.value = res.data[n.prop];
                            }
                        });
                        (result.viewItems || []).forEach(n => {
                            if (n.prop && res.data[n.prop]) {
                                n.value = res.data[n.prop];
                            }
                        });
                        vm.showResponseStr = JSON.stringify(result);
                        res.data = result;
                    }
                    // 复杂展示
                    formItems = res.data.formItems;
                    formItems = formItems.concat(res.data.viewItems || []);


                    if (res.data.viewBottomBtn) {
                        res.data.viewBottomBtn.btns.forEach(n => {
                            if (n.showWhen) {
                                var targetItem = formItems.find(m => m.prop == n.showWhen[0]);
                                n.show = (targetItem && n.showWhen[1].includes(targetItem.value));
                                // debugger
                            }
                        });
                        var viewBottomBtn = res.data.viewBottomBtn;
                        viewBottomBtn.show = viewBottomBtn.btns.some(n => n.show);
                        vm.viewBottomBtn = viewBottomBtn;
                    }
                }
                
                if (res.data.viewTopperItems) {
                    res.data.viewTopperItems.forEach(item => {
                        item.text = item.text.replace(/【([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*】/g, function (d) {
                            var prop = d.slice(1, -1);
                            var targetItem = formItems.find(m => m.prop == prop);
                            return (targetItem && targetItem.value) || '';
                        });
                        if (item.loadByProp) {
                            var statusItem = formItems.find(m => m.prop == item.loadByProp);
                            if (statusItem) {
                                var status = statusItem.value || '';
                                var iconPrefix = vm.API_PREFIX + '/mobile/wxImages/icon/';
                                if (/([未|不]通过)|(失败)/.test(status)) {
                                    item.clz = 'fail';
                                    item.icon = {url: iconPrefix + 'fail.png'};
                                } else if (/[通过|成功]/.test(status)) {
                                    item.clz = 'success';
                                    item.icon = {url: iconPrefix + 'success.png'};
                                } else if (/待[提交|上传]/.test(status)) {
                                    item.clz = 'uncomplete';
                                    item.icon = {url: iconPrefix + 'success.png'};
                                } else if (/待审|未审/.test(status)) {
                                    item.clz = 'shenhe';
                                    item.icon = {url: iconPrefix + 'shenhe.png'};
                                } else if (/取消/.test(status)) {
                                    item.clz = 'cancel';
                                    item.icon = {url: iconPrefix + 'cancel.png'};
                                } else if (/已完成/.test(status)) {
                                    item.clz = 'complete';
                                    item.icon = {url: iconPrefix + 'complete.png'};
                                } else if (/中$|等待|^未/.test(status)) {
                                    item.clz = 'processing';
                                    item.icon = {url: iconPrefix + 'processing.png'};
                                } 
                            } else {
                                item.hide = true;
                            }
                        }
                        return item;
                    });
                    vm.topperItems = res.data.viewTopperItems;
                }
                
                formItems.forEach(n => {
                    if (!n.prop) {return;}
                    !n.value && (n.value = '');
                    if (n.type == 'image') {
                        n.fileList = n.value ? n.value.split(',').map(n => {
                            return {url: vm.API_PREFIX + n, path: n}
                        }) : []
                    }
                    if (n.editWhenView) {
                        if (uni.$u.test.array(n.editWhenView)) {
                            var prop = n.editWhenView[0];
                            var targetValue = formItems.find(m => m.prop == prop);
                            n.editWhenView = (targetValue && targetValue.value == n.editWhenView[1]);
                        }
                    }
                });
                vm.formItems = formItems;
                
            });
        },
        __getReplaceUrl: function (url) {
          var vm = this;
          url = url.replace('【id】', vm.id);
          url = url.replace('【openId】', vm.openId);
          return url.replace(/【([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*】/g, function (d) {
              // debugger
              var prop = d.slice(1, -1);
              return vm.model[prop] || '';
          });
        },
        viewBottomButtonClick: function (item) {
            var vm = this;
            vm.throttle();
            function getReplaceUrl (url) {
                url = url.replace('【id】', vm.id);
                url = url.replace('【openId】', vm.openId);
                return url.replace(/【([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*】/g, function (d) {
                    var prop = d.slice(1, -1);
                    var targetItem = vm.formItems.find(n => n.prop == prop);
                    return (targetItem && targetItem.value) || '';
                });
            }
            if (item.url) {
                var url = getReplaceUrl(item.url);
                uni.navigateTo({ url });
            } else if (item.event) {
                if (item.event == 'scan') {
                    vm.scanQrCode();
                } else {
                    item.event == 'edit';
                    vm.initAndEdit();
                }
            } else if (item.h5) {
                var h5 = getReplaceUrl(item.h5);
                vm.gotoH5Page(h5);
            } else if (item.api) {
                var apiUrl = getReplaceUrl(item.api);
                uni.showModal({
                    title: '提示',
                    content: item.apiBeforeTip || '是否确定操作',
                    showCancel: true,
                    success: function(res2) {
                        if(res2.confirm) { 
                            uni.showLoading();
                            global.listPageNeedReload = true;
                            vm.getAndLoad('请求接口', apiUrl, function (res) {
                               uni.hideLoading();
                               uni.showModal({
                                   title: '提示',
                                   content: res.msg || (res.code == 0 ? '操作成功' : '操作失败'),
                                   showCancel: false,
                                   success: function(res3) {
                                       if (res3.confirm) {
                                        vm.back();
                                       }
                                   }
                               });
                            });
                        }
                        
                    }
                });
                
            }
        },
        editSingleField: function (item) {
            var vm = this;
            vm.topperItems = [];
            vm.viewBottomBtn = [];
            var originData = JSON.parse(vm.showResponseStr).data;
            vm.pageJSON = originData;
            uni.setNavigationBarTitle({
                title: item.label + '(修改)'
            });
            vm.entityId = originData.editConfig.entityId || 'id';
            vm.getXqColumns();

            var formItems = [JSON.parse(JSON.stringify(item))];
            formItems.forEach(n => {
                if (!n.prop) {
                    return;
                }
                n.value = '';
                if (n.optionApi && !n.lazySearch) {
                    n.optionApi = n.optionApi.replace('【openId】', vm.openId);
                    vm.getAndLoad('读取option列表', n.optionApi, function (res) {
                        n.options = res.data;
                        if (n.type == 'picker') {
                            n.columns = [n.options];
                        }
                    });
                } else if (n.type == 'picker' && n.options) {
                    n.columns = [n.options];
                }
                // 设置一些初始值
                if (n.type == 'checkbox') {
                    if (!n.options.map) {
                        n.options = n.options.split('$').map((m, i) => {
                            return {
                                name: m.split(':')[1],
                                active: !i,
                                value: m.split(':')[0],
                            };
                        })
                    } else {
                        n.options = n.options.map((o, i) => {
                            return { name: o, active: !i };
                        });
                    }
                }
                if (n.type == 'picker') {
                    n.showPicker = false;
                }
                if (n.type == 'areapicker') {
                    n.provinceCityArea = [];
                }
                if (n.type == 'image') {
                    !n.limit && (n.limit = 1);
                    n.fileList = [];
                }
            });
            vm.formItems = formItems;
            vm.generateModelAndRules();
            vm.viewMode = false;
            vm.editType = 'edit';
        },
        initAndEdit: function (fields) {
            var vm = this;
            vm.topperItems = [];
            vm.viewBottomBtn = [];
            var originData = JSON.parse(vm.showResponseStr).data;
            if (originData.editConfig) {
				if (originData.editConfig.title) {
				    uni.setNavigationBarTitle({
				        title: originData.editConfig.title
				    });
				}
				
				vm.entityId = originData.editConfig.entityId || 'id';

				vm.getXqColumns();
				
				vm.getAndLoad('申报的配置json', originData.editConfig.loadJSON, function (res) {
					var formItems = res.formItems;
					vm.showTxry = res.txry;
					// debugger
					vm.showBack = res.showBack;
					vm.txryFormItems = res.txryFormItems;
					vm.tip = res.tip || '';
					vm.submitTipInfo = res.submitTipInfo;
					vm.pageJSON = res;
					
					formItems.forEach(n => {
						if (!n.prop) {
							return;
						}
						if (n.optionApi && !n.lazySearch) {
							n.optionApi = n.optionApi.replace('【openId】', vm.openId);
							vm.getAndLoad('读取option列表', n.optionApi, function (res) {
								n.options = res.data;
								if (n.type == 'picker') {
									n.columns = [n.options];
								}
							});
						} else if (n.type == 'picker' && n.options) {
							n.columns = [n.options];
						}
						// 设置一些初始值
						if (n.type == 'checkbox') {
							if (!n.options.map) {
								n.options = n.options.split('$').map((m, i) => {
									return {
										name: m.split(':')[1],
										active: !i,
										value: m.split(':')[0],
									};
								})
							} else {
								n.options = n.options.map((o, i) => {
									return { name: o, active: !i };
								});
							}
						}
						if (n.type == 'picker') {
							n.showPicker = false;
						}
						if (n.type == 'areapicker') {
							n.provinceCityArea = [];
						}
						if (n.type == 'image') {
							!n.limit && (n.limit = 1);
							n.fileList = [];
						}
					});
					vm.formItems = formItems;
                    
					vm.generateModelAndRules();
					// 第一遍循环，model初步行程
					originData.formItems.forEach((originField) => {
						if (originField.prop) {
							var myItem = vm.formItems.find(n => n.prop == originField.prop);
							if (myItem) {
								vm.setModelValue(myItem.prop, originField.value);
							}
						}
					});

                    // 第二遍循环 拓展项目创建
                    var originFields = originData.formItems;
                    // debugger
                    vm.formItems.forEach(field => {
                        if (field.groupProp) { // 同行人员等
                            var bindValues = [];
                            var props = field.addFields.map(n => n.prop).filter(n => n);
                            var index = 0;
                            var hasNext = originFields.findIndex(n => n.prop.endsWith('_' + index));
                            while(hasNext != -1) {
                                let endFix = '_' + index;
                                var item = {};
                                props.forEach(n => {
                                    var targetItem = originFields.find(m => m.prop == (n + endFix));
                                    item[n] = targetItem ? targetItem.value : '';
                                });
                                bindValues.push(item);

                                index++;
                                hasNext = originFields.findIndex(n => n.prop.endsWith('_' + index));
                            }
                            vm.setArrayModelValue(field.groupProp, bindValues);
                        }
                    });

					// 第三遍循环 对需要bindId的字段，去值 需要用户重新填
					vm.formItems.forEach(n => {
						if (n.prop && n.bindId) {
							if ((typeof n.bindId == 'string' && !vm.model[n.bindId]) || (uni.$u.test.array(n.bindId) && !vm.model[n.bindId[0]])) {
								vm.model[n.prop] = '';
							}
						}
					});
					
					// debugger
					if (res.initInfoApi) {
						vm.initFormInfo(res.initInfoApi);
					}
					/*
					if (res.gaozhiBefore) {
						vm.initCommonPopup(res.gaozhiBefore, true);
					}
					*/
				    vm.viewMode = false;
					vm.editType = 'edit';
				});
			}
        },
        execH5Foo: function (item) {
            var vm = this;
            eval(item.exec);
        }
    }
};
</script>

<style lang="scss" scoped>
    .loading-icon {
        margin-top: 45vh
    }
.formPage {
    margin: 20rpx 0;
    .fieldItem {
        position: relative;
        &.candelete {
            padding-top: 40rpx;
            background: #fff;
        }
        .delete-btn {
            position: absolute;
            right: 10rpx;
            top: 5rpx;
        }
        .edit-btn {
            background: #fff;
            display: flex;
            justify-content: flex-end;
            .delete-btn {
                position: relative;
                width: 110rpx;
                top: 10rpx;
            }
        }
    }
    .imageUploader {
        .placeholder {
            color: #ff4e4e;
            font-size: 24rpx;
            position: absolute;
            left: 20rpx;
            bottom: 30rpx;
        }
    }
    /deep/ {
        .u-form-item {
            background: #fff;
            padding: 0 20rpx 0 30rpx;
        }
        .uni-input-input {
            text-align: right !important;
            font-size: 28rpx !important;
        }
        .u-input {
            background: transparent !important;
        }
        .u-form-item__body__right__message {
            text-align: right;
        }
        .long .u-textarea.u-textarea--disabled {
            overflow-y: auto;
        }
        .u-textarea {
            width: 100%;
            box-sizing: border-box;
            &.u-textarea--disabled {
                background: transparent;
                padding: 0;
                height: 50rpx;
                overflow: hidden;
                >textarea {
                    text-align: right !important;
                    font-size: 28rpx !important;
                    padding: 10rpx 0 10rpx 0;
                    min-height: 20px !important;
                    height: 60rpx !important;
                    box-sizing: border-box;
                }
            }
        }
        .pcs {
            text-align: right !important;
            font-size: 28rpx !important;
            padding: 0;
            height: 50rpx;
        }
        .u-upload__wrap {
            margin-left: auto;
        }
        .uni-input-placeholder {
            text-align: right !important;
            font-size: 28rpx !important;
        }
        .u-form-item__body__left__content__label {
            font-size: 28rpx;
        }
        .u-input__content__field-wrapper__field {
            text-align: right !important;
            font-size: 28rpx !important;
        }
        .u-form-item__body__right__content__slot {
            display: flex;
            flex-direction: row;
            region-picker {
                width: 100%;
            }
        }
        .textareaField {
            .u-form-item__body__right__content__slot {
                display: flex;
                flex-direction: column;
                align-items: baseline;
            }
        }
        .dxyzNo {
            .u-form-item__body__right__content__slot {
                // display: flex;
                // flex-direction: row;
                > .u-input--square {
                    width: 50%;
                }
                .getcode {
                    margin-left: 10px;
                    width: 180rpx;
                }
            }
        }
        .getAddress {
            padding: 0 10rpx;
        }
    }
    .gap {
        color: #999999;
        text-indent: 10px;
        margin: 10rpx 0;
        font-size: 28rpx;
        &.line {
            border-bottom: 1px solid #999999;
        }
        &.dashed {
            border-bottom: 1px dashed #999999;
        }
    }
    .text-area-label {
        font-size: 28rpx;
        line-height: 60rpx;
        color: #303133;
        margin: -10rpx 0 0 -2rpx;
        position: relative;
        .require {
            font-size: 20px;
            color: #f56c6c;
            position: absolute;
            left: -16rpx;
            top: 5rpx;
        }
        .subLabel {
            font-size: 20rpx;
        }
    }

}
.options {
    display: flex;
    margin-left: auto;
    flex-wrap: wrap;
    .option {
        color: #fff;
        min-width: 60rpx;
        text-align: center;
        background: #afabab;
        padding: 4rpx 10rpx;
        border-radius: 16rpx;
        margin-right: 10rpx;
        margin-bottom: 6rpx;
        font-size: 24rpx;
        &.active {
            background: #2788f3;
        }
    }
}
.bottom-area {
    padding: 20rpx 20rpx 40rpx;
    display: flex;
    [hidden] {
        display: none !important;
    }
    /deep/ {
        .u-button {
            margin: 0 10rpx;
        }
    }
}
.top-tip {
    color: #ff2424;
    padding: 10rpx;
    font-size: 24rpx;
}
.txry {
    margin-top: 20rpx;
    background: #fff;
    overflow: hidden;
    /deep/ .u-divider {
        margin-bottom: 0;
    }
    .delete-btn {
        width: 120rpx;
        margin: 20rpx 30rpx 10rpx auto;
    }
}
.commonpopup {
    /deep/ .u-popup__content{
        background: transparent;
        border-radius: 20rpx;
    }
    
}
.commonPopInfo {
    width: 650rpx;
    transform: translateY(-100rpx);
    >.label {
        height: 90rpx;
        line-height: 90rpx;
        text-indent: 30rpx;
    }
    .textarea {
        max-height: 700rpx;
        overflow-y: scroll;
        font-size: 26rpx;
        padding: 10rpx 30rpx;
        display: block;
    }
    .checkbox {
        padding: 10px 20rpx 0;
        zoom: 0.9;
    }
    .confirmBtn {
        padding: 0 30rpx 20rpx;
        display: flex;
        /deep/ .u-button {
            &:not(:last-child) {
                margin-right: 10rpx;
            }
        }
    }
    .body {
        background: #fff;
        border-radius: 0 0 20rpx 20rpx;
    }
    
}
.submitTipInfo {
    background: #fff;
    padding: 20rpx;
    .title {
        font-size: 30rpx;
    }
    .required {
        color: #f56c6c
    }
    .text {
        margin: 10rpx 0;
        font-size: 28rpx;
        line-height: 44rpx;
    }
}
.viewBottomBtn {
    display: flex;
    .btn {
        flex: 1;
        margin: 0 10rpx;
    }
}
.topper {
    @mixin topper-style($argus) {
      border: 1px solid $argus;
      color: $argus;
      background: rgba($argus, .15);
      .rightText {
        color: $argus;
      }
    }
    .topperItems {
        display: flex;
        margin: 20rpx;
        justify-content: center;
        align-items: center;
        border-radius: 20rpx;
        @include topper-style(#999999);
        &.success {
            @include topper-style(#00A43A);
        }
        &.cancel {
            @include topper-style(#AAAAAA);
        }
        &.complete {
            @include topper-style(#4C31B4);
        }
        &.shenhe {
            @include topper-style(#DF9018);
        }
        &.fail {
            @include topper-style(#F56C6C);
        }
        &.processing {
            @include topper-style(#07A17A);
        }
        &.uncomplete {
            @include topper-style(#00A43A);
        }
        &.complete {
            @include topper-style(#4C31B4);
        }
        .leftIcon  {
            display: flex;
            align-items: center;
            image {
                width: 28rpx;
                height: 28rpx;
                margin: 20rpx;
            }
        }
        .rightText {
            font-size: 26rpx;
        }
    }
}

</style>
